package cn.sdjzu.exercise;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SelectConfigActivity extends BasedActivity {
	TextView ipconfig;
	Button ok;
	Button no;
	TextView ip;
	TextView port;
	EditText inputip1;
	EditText inputip2;
	EditText inputip3;
	EditText inputip4;
	EditText inputport;
	String IPAndPort[];
	int Port;
	SharedPreferences preferences;
	SharedPreferences.Editor editor;
	Socket socket;
	OutputStream os;
	InputStream is;
	Handler myhandler;
	ConnThread conn;
	Toast cancelTrans, TestTransToast;
	public byte[] SET_SETTING_FORCE_PREFIX;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ExerciseApp.getInstance().addActivity(this);
		setContentView(R.layout.config);
		ipconfig = (TextView) findViewById(R.id.ipConfig);
		ipconfig.setText("IP and PORT");
		ok = (Button) findViewById(R.id.getIPAndPort3);
		no = (Button) findViewById(R.id.NogetIPAndPort);
		ip = (TextView) findViewById(R.id.IP);
		port = (TextView) findViewById(R.id.PORT);
		inputip1 = (EditText) findViewById(R.id.inputIP1);
		inputip2 = (EditText) findViewById(R.id.inputIP2);
		inputip3 = (EditText) findViewById(R.id.inputIP3);
		inputip4 = (EditText) findViewById(R.id.inputIP4);
		inputip1.setText("" + 192);
		inputip2.setText("" + 168);
		inputip3.setText("" + 0);
		inputip4.setText("" + 104);
		inputport = (EditText) findViewById(R.id.inputPORT);
		inputport.setText("" + 8899);
		preferences = getSharedPreferences("itYao", Context.MODE_WORLD_READABLE);
		editor = preferences.edit();
		socket = new Socket();
		TransToast = Toast.makeText(getApplicationContext(),
				"连接失败,请检查IP与端口或者重新选择通讯方式！", Toast.LENGTH_LONG);
		TestTransToast = Toast.makeText(getApplicationContext(), "连接成功！",
				Toast.LENGTH_LONG);
		cancelTrans = Toast.makeText(getApplicationContext(),
				"未配置通讯，不能进行训练！！！", Toast.LENGTH_LONG);
		SET_SETTING_FORCE_PREFIX = new byte[] { (byte) 0x01, (byte) 0x10,
				(byte) 0x00, (byte) 0x6D, (byte) 0x00, (byte) 0x01,
				(byte) 0x02, };
		ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String ip = inputip1.getText().toString().trim() + "."
						+ inputip2.getText().toString().trim() + "."
						+ inputip3.getText().toString().trim() + "."
						+ inputip4.getText().toString().trim();
				String getport = inputport.getText().toString().trim();
				IPAndPort[0] = ip;
				IPAndPort[1] = getport;
				Port = Integer.parseInt(IPAndPort[1]);
				conn = new ConnThread(IPAndPort[0], Port);
				conn.start();
			}
		});
		no.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelTrans.show();
				Intent intent = new Intent(SelectConfigActivity.this,
						ControlPanelActivity.class);
				startActivity(intent);
				SelectConfigActivity.this.finish();
				onDestroy();
			}
		});
		myhandler = new Handler() {
			public void handleMessage(Message msg) {
				boolean xy = socket.isConnected();
				if (xy) {
					try {
						os.write(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, 100));
					} catch (Exception e) {
						e.printStackTrace();
					}
					TestTransToast.show();
					editor.putString("IP", IPAndPort[0]);
					editor.putInt("port", Port);
					editor.commit();
					Intent intent = new Intent(SelectConfigActivity.this,
							ControlPanelActivity.class);
					startActivity(intent);
					SelectConfigActivity.this.finish();
				} else {
					Toast.makeText(getApplicationContext(), "连接失败",
							Toast.LENGTH_LONG);
				}
			}
		};
	}

	class ConnThread extends Thread {
		public String IP;
		public int port;

		public ConnThread(String IP, int port) {
			this.IP = IP;
			this.port = port;
		}

		@Override
		public void run() {
			try {
				SocketAddress remoteAddr = new InetSocketAddress(this.IP,
						this.port);
				socket.connect(remoteAddr);
				os = socket.getOutputStream();
				is = socket.getInputStream();
				Message msg = new Message();
				msg.what = 1;
				myhandler.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
				TransToast.show();
				Intent intent = new Intent(SelectConfigActivity.this,
						ControlPanelActivity.class);
				startActivity(intent);
				SelectConfigActivity.this.finish();
				onDestroy();
			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		IPAndPort = new String[2];
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (socket.isConnected()) {
			try {
				os.close();
				is.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			finish();
		}
	};

	public void onBackPressed() {
		close();
	}
}
